package com.jf.yytgd.config;

import com.jf.yytgd.exception.IllegalTableException;
import com.jf.yytgd.utils.SqlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2025-01-12
 * Time:17:30
 */
@Slf4j
@Configuration
public class DatabaseInitializationConfig {
    private static final String CHECK_EXIST_START_SQL = "show tables like 'start'";
    private static final String CHECK_STARTED_SQL = "select `is_first_start` from `start` where `id` = 1";
    private static final String INSERT_START_SQL = "insert into `start` values(1,0)";
    private static final String UPDATE_START_SQL = "update `start` set `is_first_start` = 0 where `id` = 1";
    private static final String CREATE_TABLE_SCRIPT_PATH = "sql/create_table.sql";
    private static boolean start_has_data = false;

    @Bean
    public CommandLineRunner commandLineRunner(JdbcTemplate jdbcTemplate) {
        return new CommandLineRunner() {
            @Override
            public void run(String... args) {
                if (checkFirst(jdbcTemplate)) {
                    SqlUtil.executeSqlScript(CREATE_TABLE_SCRIPT_PATH);
                    if (!start_has_data) {
                        jdbcTemplate.update(INSERT_START_SQL);
                    } else {
                        jdbcTemplate.update(UPDATE_START_SQL);
                    }
                }
            }
        };
    }

    private boolean checkFirst(JdbcTemplate jdbcTemplate) {
        String startTable;
        try {
            startTable = jdbcTemplate.queryForObject(CHECK_EXIST_START_SQL, String.class);
        } catch (DataAccessException e) {
            log.info("Start creating tables");
            return true;
        }
        if (startTable != null && !startTable.equals("start")) {
            throw new IllegalTableException(startTable);
        }
        try {
            Boolean is_started = jdbcTemplate.queryForObject(CHECK_STARTED_SQL, Boolean.class);
            start_has_data = true;
            return Boolean.TRUE.equals(is_started);
        } catch (DataAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
